<template>
    <div>
      <el-form :disabled="pageModel.readOnly" :model="pageModel" :rules="equityRules" ref="equityForm" class="clearfix box-body">
        <el-form-item style="flex-shrink: 0;" label="" prop="equityName">
          <el-input
            v-model="pageModel.equityName"
            :maxlength="200"
            placeholder="权益名称"
            class="filter-item fl"/>
        </el-form-item>
        <el-form-item style="flex-shrink: 0;" label="" prop="equityType">
          <el-select v-model="pageModel.equityType" placeholder="权益类型">
            <el-option v-for="item in gradeOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item style="flex-shrink: 0;" label="" prop="name">
          <el-input
            v-model="pageModel.remark"
            :maxlength="200"
            placeholder="权益备注"
            class="filter-item fl"/>
        </el-form-item>
        <el-form-item style="flex-shrink: 0;" label="" prop="name">
          <el-select v-model="pageModel.equityStatus" placeholder="状态">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
      <el-divider style="margin:0"></el-divider>
      <div class="box-body edit-grade-list clearfix">
        <div class="attribute-operation2 fr clearfix">
          <el-button
            v-if="!pageModel.readOnly"
            type="text"
            @click="addLevel()">
            添加等级
          </el-button>
        </div>
        <div class="table-responsive">
          <el-form
            :disabled="pageModel.readOnly"
            :model="pageModel"
            :rules="equityLevelRules"
            ref="levelForm"
          >
            <el-table
              :data="pageModel.equityLevelDef"
              :show-header="false"
              style="width: 100%;"
            >
              <el-table-column
                prop="equityLevel"
                min-width="8%"
                align="left">
                <template slot-scope="scope">
                  <el-form-item :prop="'equityLevelDef.' + scope.$index + '.equityLevel'"
                                :rules="equityLevelRules.equityLevel" style="margin-bottom: 5px;">
                    <el-input
                      v-model.number="scope.row.equityLevel"
                      :maxlength="200"
                      placeholder="排序"
                      class="filter-item fl"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="equityLevelName"
                min-width="20%"
                align="left">
                <template slot-scope="scope">
                  <el-form-item :prop="'equityLevelDef.' + scope.$index + '.equityLevelName'"
                                :rules="equityLevelRules.equityLevelName" style="margin-bottom: 5px;">
                    <el-input
                      v-model.trim="scope.row.equityLevelName"
                      :maxlength="10"
                      placeholder="等级名称"
                      class="filter-item fl"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="equityLevelRemarks"
                min-width="65%"
                align="left">
                <template slot-scope="scope">
                  <el-form-item style="margin-bottom: 5px;">
                    <el-input
                      v-model.trim="scope.row.equityLevelRemarks"
                      :maxlength="200"
                      placeholder="描述"
                      class="filter-item fl"/>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                v-if="!pageModel.readOnly"
                min-width="7%"
                align="left">
                <template slot-scope="scope">
                    <el-button type="text" @click="deleteLevel(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </div>
      <el-divider></el-divider>
      <el-form style="margin-top:10px;" v-if="!pageModel.readOnly" :inline="true" :model="pageModel" class="demo-form-inline fr" @submit.native.prevent>
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="serviceName" @keyup.enter.native="searchService"
                    placeholder="请输入服务名称"></el-input>
        </el-form-item>
        <el-form-item>
          <button class="btn btn-default" type="button" @click="searchService">查询</button>
        </el-form-item>
      </el-form>
      <div class="box-body clearfix">
        <div class="table-responsive">
          <el-table
            :data="shownServiceArray"
            :cell-style="changeCellStyle"
            :header-cell-style="headerRowClassName"
            fit
            highlight-current-row
            style="width: 100%;"
          >
            <el-table-column
              label="项目名称"
              prop="serviceName"
              align="left">
            </el-table-column>
            <el-table-column
              label="项目内容简介"
              prop="serviceIntr"
              align="left">
            </el-table-column>
            <el-table-column
              label="使用流程"
              prop="serviceProcess"
              align="left">
            </el-table-column>
            <el-table-column
              label="使用通道"
              prop="serviceChannel"
              align="left">
            </el-table-column>
            <el-table-column
              v-for="(item, index) in pageModel.equityLevelDef"
              :key="index"
              :label="item.equityLevelName"
              align="left">
              <template slot-scope="scope">
                <el-checkbox :checked="!!checkedServices[index] && !!checkedServices[index] && !!checkedServices[index][scope.row.serviceID]"
                             @change="serviceCheck($event, scope.row, item, index)"
                             :disabled="pageModel.readOnly"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="attribute-operation clearfix fr">
          <el-button v-if="!pageModel.readOnly" type="primary" @click="save()">保存</el-button>
          <el-button @click="close">关闭</el-button>
        </div>
      </div>
    </div>
</template>

<script>
  import * as Api from '../../../api/rightsManagement';

  export default {
    name: 'EditEquity',
    props: {
      serviceArray: {
        type: Array,
        default: true
      },
      equity: {required: true, type: Object}
    },
    data() {
      return {
        serviceName: '',
        pageModel: {},
        equityLevelRules: {
          equityLevel: [
            {required: true, message: "请输入排序", trigger: "change"},
            {type: 'number', message: '必须为数字值'}
          ],
          equityLevelName: [
            {required: true, message: '请输入等级名称', trigger: 'blur'}
          ]
        },
        equityRules: {
          equityName: [
            {required: true, message: '请输入权益名称', trigger: 'blur'}
          ],
          equityType: [
            {required: true, message: '请选择权益类型', trigger: 'blur'}
          ]
        },
        gradeOptions: [
          {
            label: '保单权益',
            value: 1
          },
          {
            label: '客户权益',
            value: 2
          }
        ],
        typeOptions: [ // 状态
          {
            label: '正常',
            value: 0
          },
          {
            label: '停止服务',
            value: 1
          }
        ],
        shownServiceObject: {},
        shownServiceArray: [],
        checkedServices: [],
        changed: false
      }
    },
    computed: {
      levelKey: {
        get() {
          return 'c' + new Date().getTime();
        }
      }
    },
    created() {
      this.pageModel = JSON.parse(JSON.stringify(this.equity));
      // console.log('create:::::', this.serviceArray);
      let serviceObj = {};
      let checkedServices = [];
      this.pageModel.equityLevelDef.forEach((el, idx) => {
        checkedServices[idx] = {};
        el.serviceLevelDef.forEach(s => {
          if (!serviceObj[s.serviceID]) {
            let e = this.serviceArray.find(ss => {
              // console.log('compare::::', s.serviceID, ss.serviceID);
              return ss.serviceID === s.serviceID;
            });
            // if (!e) {
            //   debugger;
            //   console.log('serviceID not found:::', s.serviceID);
            // }
            serviceObj[s.serviceID] = e;
          }
          // console.log('check services', idx, checkedServices[idx]);
          checkedServices[idx][s.serviceID] = s;
        })
      })
      this.checkedServices = checkedServices;
      this.shownServiceArray = Object.values(serviceObj);
      //console.log('service array1', serviceObj, Object.values(serviceObj))
      this.shownServiceObject = serviceObj;
      // console.log('checked:::', this.pageModel, checkedServices);
    },
    methods: {
      close() {
        this.$emit('close', this.changed);
      },
      addLevel() {
        let len = 0
        if (this.pageModel.equityLevelDef.length > 0) {
          len = this.pageModel.equityLevelDef[this.pageModel.equityLevelDef.length - 1].equityLevel
          len += 1
        }
        let obj = {
          equityLevelName: null, // 权益等级名称
          equityLevelRemarks: null, // 权益等级备注
          equityLevel: len,
          serviceLevelDef: []
        }

        this.checkedServices.push({});
        this.pageModel.equityLevelDef.push(obj)
        // console.log('1111');
      },
      deleteLevel(idx) {
        // console.log('aaaaa', idx, this.checkedServices);
        if (Object.keys(this.checkedServices[idx]).length) {
          this.$confirm('内含有已配服务，确定删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$delete(this.pageModel.equityLevelDef, idx);
            this.$delete(this.checkedServices, idx);
            // this.pageModel.equityLevelDef.splice(idx, 1);
            // this.checkedServices.splice(idx, 1);
            // this.$forceUpdate();
          }).catch(() => void(0));
        } else {

          // if (idx < this.checkedServices.length - 1) {
          //   // 先把右侧列值复制过来，防止刷新页面时不出现对勾
          //   this.checkedServices[idx] = this.checkedServices[idx+1];
          // }
          this.$delete(this.checkedServices, idx);
          // this.$delete(this.pageModel.equityLevelDef, idx);
          let t = this.pageModel.equityLevelDef.map(e => e);
          t.splice(idx, 1)
          this.pageModel.equityLevelDef = [];
          setTimeout(() => {
            // 避免界面刷新bug，增加一个等待，否则界面刷新显示不正确
            this.pageModel.equityLevelDef = t;
          }, 50);
          // console.log('bbbb', this.pageModel, this.checkedServices);
        }
      },
      save() {
        this.$refs['equityForm'].validate((valid) => {
          if (valid) {
            this.$refs['levelForm'].validate((valid) => {
              if (valid) {
                this.doSave();
              } else {
                this.$message.error('页面上有错误');
                return false;
              }
            });
          } else {
            this.$message.error('页面上有错误');
            return false;
          }
        });
      },
      doSave() {
        let entity = {
          equityID: this.pageModel.equityID,
          equityName: this.pageModel.equityName,
          equityStatus: this.pageModel.equityStatus,
          equityType: this.pageModel.equityType,
          remark: this.pageModel.remark,
          equityLevelDef: []
        };
        this.pageModel.equityLevelDef.forEach((el, idx) => {
          let equityLevel = {
            equityLevelID: el.equityLevelID,
            equityLevel: el.equityLevel,
            equityLevelName: el.equityLevelName,
            equityLevelRemarks: el.equityLevelRemarks,
            serviceLevelDef: []
          };
          Object.values(this.checkedServices[idx]).forEach(service => equityLevel.serviceLevelDef.push(service));
          entity.equityLevelDef.push(equityLevel);
        });
        // console.log('entity:', this.pageModel, entity);
        Api.updateEquity(entity).then(resp => {
          this.$message.success('保存成功');
          this.changed = true;
        })
      },
      searchService() {
        let showObject = {};
        this.serviceArray.forEach(s => {
          this.checkedServices.forEach(lvServiceObj => {
            Object.values(lvServiceObj).forEach(ss => {
              if (ss.serviceID === s.serviceID) {
                showObject[s.serviceID] = s;
              }
            })
          });
        });

        this.serviceArray.forEach(s => {
          if (!this.serviceName || s.serviceName.indexOf(this.serviceName) > -1) {
            // this.shownServiceObject[s.serviceID] = s;
            showObject[s.serviceID] = s;
          }
        });

        this.checkedServices.forEach(lvServiceObj => {
          Object.keys(lvServiceObj).forEach(checkServiceID => {
            if (!showObject[checkServiceID]) {
              delete lvServiceObj[checkServiceID];
            }
          })
        })


        this.shownServiceObject = showObject;
        this.shownServiceArray = [];
        setTimeout(() => {
          this.shownServiceArray = Object.values(this.shownServiceObject);
          console.log('service array', Object.values(this.shownServiceObject))
        }, 100);

      },
      serviceCheck(event, service, lvlItem, index) {
        if (event) {
          this.$set(this.checkedServices[index], service.serviceID, service);
          // this.checkedServices[index][service.serviceID] = service;
        } else {
          delete this.checkedServices[index][service.serviceID];
        }
        // console.log(index, service, this.checkedServices);
      },
      changeCellStyle({row, column, rowIndex, columnIndex}) {
        if (columnIndex === 0) {
          return 'background: #eaeaec;color: #888888;'
        } else if (columnIndex === 1) {
          return 'color: #3E739D;'
        } else if (columnIndex === 2) {
          return 'color: #0090D9;'
        } else if (columnIndex === 3) {
          return 'color: #37A8AF;'
        }
      },
      headerRowClassName(row, column, rowIndex, columnIndex) {
        if (row.columnIndex === 0) {
          return 'background: #eaeaec;color: #888888;'
        } else if (row.columnIndex === 1) {
          return 'background: #3E739D;color: #ffffff;'
        } else if (row.columnIndex === 2) {
          return 'background: #0090D9;color: #ffffff;'
        } else if (row.columnIndex === 3) {
          return 'background: #37A8AF;color: #ffffff;'
        } else if (row.columnIndex > 3) {
          return 'background: #f56954;color: #ffffff;'
        }
      },
    }
  }
</script>

<style scoped>
  .el-divider--horizontal {
    margin: 0 0;
  }

  .el-form-item {
    margin-bottom: 5px;
  }
</style>
